<template>
  <view class="appointment-food">
    <!-- 表单区域 -->
    <view class="form-container">
      <!-- 须知提示横幅 -->
      <view class="notice-banner" @click="showNotice">
        <view class="notice-banner-content">
          <uni-icons type="info-filled" size="20" color="#ff9800"></uni-icons>
          <text class="notice-banner-text">重要提示：点击查看预约须知</text>
          <uni-icons type="right" size="16" color="#ff9800"></uni-icons>
        </view>
      </view>

      <!-- 入场时间选择 -->
      <!-- <view class="time-section">
        <view class="section-header">
          <text class="section-title required">入场时间</text>
        </view>
        <view class="time-selector">
          <view class="time-item">
            <text class="time-label">选择日期</text>
            <picker mode="date" @change="dateChange" :value="formData.appointmentDate" :start="minDate" :end="maxDate">
              <view class="time-picker">
                <text class="time-value">{{ formData.appointmentDate || '请选择日期' }}</text>
                <uni-icons type="calendar" size="20" color="#999"></uni-icons>
              </view>
            </picker>
          </view>

          <view class="time-item">
            <text class="time-label">选择时间</text>
            <picker mode="time" @change="timeChange" :value="formData.appointmentTime">
              <view class="time-picker">
                <text class="time-value">{{ formData.appointmentTime || '请选择时间' }}</text>
                <uni-icons type="clock" size="20" color="#999"></uni-icons>
              </view>
            </picker>
          </view>
        </view>
        <text class="time-tip">* 默认为明天早上6点，请根据实际情况调整</text>
      </view> -->

      <!-- 入场车辆选择 -->
      <view class="vehicle-section">
        <view class="section-header">
          <text class="section-title required">入场车辆</text>
        </view>
        <view class="vehicle-selector-wrapper">
          <view class="picker-with-add">
            <picker @change="handleVehicleChange" :value="vehicleIndex" :range="vehicleListWithInput" range-key="label" class="picker-main">
              <view class="picker">
                <text class="picker-text">{{ formData.vehicleNo || '请选择车辆' }}</text>
                <uni-icons type="bottom" size="16" color="#999"></uni-icons>
              </view>
            </picker>
            <view class="add-btn" @click="addVehicle">
              <uni-icons type="plus" size="16" color="#1890ff"></uni-icons>
            </view>
          </view>
        </view>
        <text class="vehicle-tip" v-if="defaultVehicle && formData.vehicleNo === defaultVehicle">* 已自动选择默认车辆</text>
      </view>

      <!-- 已添加的产品列表 -->
      <view class="added-products-section" v-if="addedProducts.length > 0">
        <view v-for="(product, index) in addedProducts" :key="index" class="added-product-item">
          <view class="product-header" @click.stop="toggleProductExpand(index)" :hover-class="'product-header-hover'" :hover-stay-time="50">
            <text class="product-title">产品 {{ index + 1 }}: {{ product.goodsName || '未选择' }}</text>
            <view class="expand-icon">
              <uni-icons :type="expandedProducts[index] ? 'top' : 'bottom'" size="20" color="#999"></uni-icons>
              <text class="expand-text">{{ expandedProducts[index] ? '收起' : '编辑' }}</text>
            </view>
          </view>

          <view class="product-summary" v-if="!expandedProducts[index]">
            <text class="summary-title">{{ product.productTypeName }}</text>
            <text class="summary-subtitle">{{ product.goodsName }}·{{ product.quantity }}kg</text>
            <text class="summary-subtitle" v-if="product.vehicleNo">车辆: {{ product.vehicleNo }}</text>
          </view>

          <!-- 展开后显示可编辑的表单 -->
          <view class="product-edit-form" v-if="expandedProducts[index]">
            <!-- 供货商 -->
            <view class="form-row">
              <text class="label">供货商</text>
              <view class="picker-with-add">
                <picker
                  @change="(e) => updateProductSupplier(index, e)"
                  :value="product.supplierIndex"
                  :range="supplierList"
                  range-key="supplierName"
                  class="picker-main"
                >
                  <view class="picker">
                    <text class="picker-text">{{ product.supplierName || '请选择供货商' }}</text>
                    <uni-icons type="bottom" size="16" color="#999"></uni-icons>
                  </view>
                </picker>
                <view class="add-btn" @click="addSupplier">
                  <uni-icons type="plus" size="16" color="#1890ff"></uni-icons>
                </view>
              </view>
            </view>

            <!-- 产品名称 -->
            <view class="form-row">
              <text class="label">产品名称</text>
              <view class="picker-with-add">
                <picker
                  @change="(e) => updateProductGoods(index, e)"
                  :value="product.goodsIndex"
                  :range="product.goodsListForProduct || []"
                  range-key="goodsName"
                  class="picker-main"
                >
                  <view class="picker">
                    <text class="picker-text">{{ product.goodsName || '请选择产品' }}</text>
                    <uni-icons type="bottom" size="16" color="#999"></uni-icons>
                  </view>
                </picker>
                <view class="add-btn" @click="addGoods">
                  <uni-icons type="plus" size="16" color="#1890ff"></uni-icons>
                </view>
              </view>
            </view>

            <!-- 入场车辆 -->
            <view class="form-row">
              <text class="label">入场车辆</text>
              <view class="vehicle-selector">
                <view class="picker-with-add">
                  <picker
                    @change="(e) => updateProductVehicle(index, e)"
                    :value="product.vehicleIndex || 0"
                    :range="vehicleListWithInput"
                    range-key="label"
                    class="picker-main"
                  >
                    <view class="picker">
                      <text class="picker-text">{{ product.vehicleNo || '请选择车辆' }}</text>
                      <uni-icons type="bottom" size="16" color="#999"></uni-icons>
                    </view>
                  </picker>
                  <view class="add-btn" @click="addVehicle">
                    <uni-icons type="plus" size="16" color="#1890ff"></uni-icons>
                  </view>
                </view>
              </view>
            </view>

            <!-- 数量 -->
            <view class="form-row">
              <text class="label">数量 (kg)</text>
              <view class="quantity-control">
                <button class="quantity-btn" @click="updateProductQuantity(index, -1)">-</button>
                <input
                  class="quantity-input"
                  :value="product.quantity"
                  @input="(e) => updateProductField(index, 'quantity', e.detail.value)"
                  type="number"
                />
                <button class="quantity-btn" @click="updateProductQuantity(index, 1)">+</button>
              </view>
            </view>

            <!-- 产品类型 -->
            <view class="section-area">
              <text class="section-title">产品类型</text>
              <view class="product-types">
                <view
                  class="type-item"
                  :class="{ active: product.productType === item.value }"
                  v-for="item in productTypes"
                  :key="item.value"
                  @click="updateProductField(index, 'productType', item.value)"
                >
                  <view class="type-icon">
                    <uni-icons :type="item.icon" size="24" :color="product.productType === item.value ? '#1890ff' : '#999'"></uni-icons>
                  </view>
                  <text class="type-text">{{ item.label }}</text>
                </view>
              </view>
            </view>

            <!-- 产地信息 -->
            <view class="section-area">
              <text class="section-title">产地信息</text>
              <view class="address-tags">
                <view class="address-tag active">
                  <text class="address-tag-text">{{ product.province || '河南省' }}</text>
                </view>
                <view class="address-tag" :class="{ active: product.city }">
                  <picker mode="selector" :range="cities" @change="(e) => updateProductField(index, 'city', cities[e.detail.value])">
                    <text class="address-tag-text">{{ product.city || '选择市' }}</text>
                  </picker>
                </view>
                <view class="address-tag" :class="{ active: product.district }">
                  <picker mode="selector" :range="districts" @change="(e) => updateProductField(index, 'district', districts[e.detail.value])">
                    <text class="address-tag-text">{{ product.district || '选择区' }}</text>
                  </picker>
                </view>
              </view>
              <view class="street-input-wrapper">
                <input
                  class="street-input"
                  :value="product.streetAddress"
                  @input="(e) => updateProductField(index, 'streetAddress', e.detail.value)"
                  placeholder="请输入街道/乡镇"
                />
              </view>
            </view>

            <!-- 进货凭证 -->
            <view class="section-area">
              <text class="section-title required">进货凭证</text>
              <ImageUploader
                :initialImageUrl="product.purchaseVoucher"
                @upload-complete="uploadProductPurchaseVoucher(index, $event)"
                :showRemove="false"
              />

              <!-- 畜牧业产品特有字段：动物检疫合格证明 -->
              <view v-if="product.productType === '2'">
                <text class="section-title required" style="margin-top: 30rpx">动物检疫合格证明</text>
                <ImageUploader
                  :initialImageUrl="product.animalQuarantineCert"
                  @upload-complete="uploadProductAnimalQuarantineCert(index, $event)"
                  :showRemove="false"
                />
              </view>

              <!-- 畜牧业产品特有字段：肉品品质检验合格证 -->
              <view v-if="product.productType === '2'">
                <text class="section-title required" style="margin-top: 30rpx">肉品品质检验合格证</text>
                <ImageUploader
                  :initialImageUrl="product.meatQualityCert"
                  @upload-complete="uploadProductMeatQualityCert(index, $event)"
                  :showRemove="false"
                />
                <!-- 三个凭证缺一不可的提示 -->
                <view class="warning-text" style="margin-top: 20rpx">
                  <text>三个凭证缺一不可</text>
                </view>
              </view>

              <!-- 承诺达标合格证（非畜牧业产品才显示） -->
              <view v-if="product.productType !== '2'">
                <view style="margin-top: 30rpx" class="cert-title-container">
                  <text class="section-title">承诺达标合格证</text>
                  <text class="upload-note-inline">（不上传生成黄码）</text>
                </view>
                <ImageUploader
                  :initialImageUrl="product.qualificationCert"
                  @upload-complete="uploadProductQualificationCert(index, $event)"
                  :showRemove="false"
                />
              </view>
            </view>

            <!-- 操作按钮 -->
            <view class="detail-actions">
              <view class="detail-btn save-btn" @click="saveProduct(index)">
                <uni-icons type="checkmarkempty" size="16" color="#1890ff"></uni-icons>
                <text class="save-text">保存</text>
              </view>
              <view class="detail-btn delete-btn" @click="removeProduct(index)">
                <uni-icons type="trash" size="16" color="#ff4d4f"></uni-icons>
                <text class="delete-text">删除</text>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 当前编辑的产品表单 -->
      <view class="current-product-form">
        <view class="form-title">
          <text>{{ addedProducts.length > 0 ? '添加新产品' : '添加第一个产品' }}</text>
        </view>

        <form @submit="submitForm">
          <!-- 基本信息 -->
          <view class="form-row">
            <text class="label">供货商</text>
            <view class="picker-with-add">
              <picker @change="supplierChange" :value="supplierIndex" :range="supplierList" range-key="supplierName" class="picker-main">
                <view class="picker">
                  <text class="picker-text">{{ supplierIndex > -1 ? supplierList[supplierIndex].supplierName : '请选择供货商' }}</text>
                  <uni-icons type="bottom" size="16" color="#999"></uni-icons>
                </view>
              </picker>
              <view class="add-btn" @click="addSupplier">
                <uni-icons type="plus" size="16" color="#1890ff"></uni-icons>
              </view>
            </view>
          </view>

          <view class="form-row">
            <text class="label">产品名称</text>
            <view class="picker-with-add">
              <picker @change="goodsChange" :value="goodsIndex" :range="goodsList" range-key="goodsName" class="picker-main">
                <view class="picker">
                  <text class="picker-text">{{ goodsIndex > -1 ? goodsList[goodsIndex].goodsName : '请选择产品名称' }}</text>
                  <uni-icons type="bottom" size="16" color="#999"></uni-icons>
                </view>
              </picker>
              <view class="add-btn" @click="addGoods">
                <uni-icons type="plus" size="16" color="#1890ff"></uni-icons>
              </view>
            </view>
          </view>

          <view class="form-row">
            <text class="label">数量 (kg)</text>
            <view class="quantity-control">
              <button class="quantity-btn" @click="decreaseQuantity">-</button>
              <input class="quantity-input" v-model="formData.quantity" type="number" placeholder="1" />
              <button class="quantity-btn" @click="increaseQuantity">+</button>
            </view>
          </view>

          <!-- 产品类型 -->
          <view class="section-area">
            <text class="section-title">产品类型</text>
            <view class="product-types">
              <view
                class="type-item"
                :class="{ active: formData.productType === item.value }"
                v-for="item in productTypes"
                :key="item.value"
                @click="selectProductType(item.value)"
              >
                <view class="type-icon">
                  <uni-icons :type="item.icon" size="24" :color="formData.productType === item.value ? '#1890ff' : '#999'"></uni-icons>
                </view>
                <text class="type-text">{{ item.label }}</text>
              </view>
            </view>
          </view>

          <!-- 产地信息 -->
          <view class="section-area">
            <text class="section-title">产地信息</text>
            <view class="address-tags">
              <view class="address-tag" :class="{ active: selectedProvince }">
                <picker mode="selector" :range="provinces" @change="onProvinceChange">
                  <text class="address-tag-text">{{ selectedProvince || '选择省' }}</text>
                </picker>
              </view>
              <view class="address-tag" :class="{ active: selectedCity }">
                <picker mode="selector" :range="cities" @change="onCityChange" :disabled="!selectedProvinceId">
                  <text class="address-tag-text">{{ selectedCity || '选择市' }}</text>
                </picker>
              </view>
              <view class="address-tag" :class="{ active: selectedDistrict }">
                <picker mode="selector" :range="districts" @change="onDistrictChange" :disabled="!selectedCityId">
                  <text class="address-tag-text">{{ selectedDistrict || '选择区' }}</text>
                </picker>
              </view>
            </view>
            <view class="street-input-wrapper">
              <input class="street-input" v-model="formData.streetAddress" placeholder="请选择街道/乡镇" />
            </view>
          </view>

          <!-- 进货凭证 -->
          <view class="section-area">
            <text class="section-title required">进货凭证</text>
            <ImageUploader
              :initialImageUrl="formData.purchaseVoucher"
              @upload-complete="handlePurchaseVoucherUpload"
              uploadText="点击上传进货凭证图片"
              uploadHint="需包含商品名称、数量、农批市场签章"
            />

            <!-- 畜牧业产品特有字段：动物检疫合格证明 -->
            <view v-if="formData.productType === '2'">
              <text class="section-title required" style="margin-top: 30rpx">动物检疫合格证明</text>
              <ImageUploader
                :initialImageUrl="formData.animalQuarantineCert"
                @upload-complete="handleAnimalQuarantineCertUpload"
                uploadText="点击上传动物检疫合格证明图片"
                uploadHint="需包含动物检疫合格证明"
              />
            </view>

            <!-- 畜牧业产品特有字段：肉品品质检验合格证 -->
            <view v-if="formData.productType === '2'">
              <text class="section-title required" style="margin-top: 30rpx">肉品品质检验合格证</text>
              <ImageUploader
                :initialImageUrl="formData.meatQualityCert"
                @upload-complete="handleMeatQualityCertUpload"
                uploadText="点击上传肉品品质检验合格证图片"
                uploadHint="需包含肉品品质检验合格证"
              />
              <!-- 三个凭证缺一不可的提示 -->
              <view class="warning-text" style="margin-top: 20rpx">
                <text>三个凭证缺一不可</text>
              </view>
            </view>

            <!-- 承诺达标合格证（非畜牧业产品才显示） -->
            <view v-if="formData.productType !== '2'">
              <view style="margin-top: 30rpx" class="cert-title-container">
                <text class="section-title">承诺达标合格证</text>
                <text class="upload-note-inline">（不上传生成黄码）</text>
              </view>
              <ImageUploader
                :initialImageUrl="formData.qualificationCert"
                @upload-complete="handleQualificationCertUpload"
                uploadText="点击上传承诺达标合格证图片"
                uploadHint="需包含承诺达标合格证"
              />
            </view>
          </view>

          <!-- 添加产品按钮 -->
          <view class="add-product-btn" @click="addProduct">
            <uni-icons type="plus" size="20" color="#1890ff"></uni-icons>
            <text class="add-text">添加产品</text>
          </view>

          <!-- 提交按钮 -->
          <button class="submit-btn" :class="{ 'submit-btn-active': canSubmit || addedProducts.length > 0 }" form-type="submit">
            {{ submitButtonText }}
          </button>
        </form>
      </view>
    </view>

    <!-- 入场须知弹窗 -->
    <view class="notice-container" v-if="showNoticePopup">
      <view class="mask" @click="hideNotice"></view>

      <view class="notice-popup">
        <text class="notice-title">预约须知</text>

        <view class="notice-content">
          <view class="notice-section">
            <text class="section-title">一、预约申请要求</text>
            <view class="notice-item">
              <text class="item-number">1.</text>
              <text class="item-text">请如实填写产品信息，确保信息准确无误</text>
            </view>
            <view class="notice-item">
              <text class="item-number">2.</text>
              <text class="item-text">上传的凭证图片需清晰可见，信息完整</text>
            </view>
            <view class="notice-item">
              <text class="item-number">3.</text>
              <text class="item-text">畜牧业产品必须上传三个凭证，缺一不可</text>
            </view>
          </view>

          <view class="notice-section">
            <text class="section-title">二、预约时间规定</text>
            <view class="notice-item">
              <text class="item-number">1.</text>
              <text class="item-text">预约申请提交后，请在预约入场时间内完成入场验证</text>
            </view>
            <view class="notice-item">
              <text class="item-number">2.</text>
              <text class="item-text">超出入场时间后，没有进行入场验证的视为逾期</text>
            </view>
            <view class="notice-item">
              <text class="item-number">3.</text>
              <text class="item-text">逾期未验证需重新提交预约申请</text>
            </view>
          </view>

          <view class="notice-section">
            <text class="section-title">三、注意事项</text>
            <view class="notice-item">
              <text class="item-number">1.</text>
              <text class="item-text">凭证不全或信息不符将导致审核不通过</text>
            </view>
            <view class="notice-item">
              <text class="item-number">2.</text>
              <text class="item-text">黄码产品需在指定区域卸货，接受进一步检查</text>
            </view>
            <view class="notice-item">
              <text class="item-number">3.</text>
              <text class="item-text">如有疑问，请联系现场工作人员</text>
            </view>
          </view>
        </view>

        <button class="confirm-btn" @click="hideNotice">我知道了</button>
      </view>
    </view>
  </view>
</template>

<script>
import { mySupplierList } from '@/api/system/supplier.js';
import { getCurrentMerchantInfo } from '@/api/system/merchant.js';
import { submitAppointment } from '@/api/system/appointment.js';
import { getProvinces, getCitiesByProvinceId, getDistrictsByCityId } from '@/api/region.js';
import upload from '@/utils/upload';
import { getCurrentUserMarket } from '@/api/market';
import { isHttp } from '@/utils/validate';
import config from '@/config';
import ImageUploader from '@/components/image-uploader.vue';
const baseUrl = config.baseUrl;

export default {
  components: {
    ImageUploader,
  },
  data() {
    return {
      // 首次加载标志
      isFirstLoad: true,
      // 当前市场信息
      currentMarketId: null,
      currentMarketName: null,
      // 已添加的产品列表
      addedProducts: [],
      // 已添加产品的展开/收起状态
      expandedProducts: {},
      // 当前正在编辑的产品数据
      formData: {
        supplierId: '',
        goodsId: '',
        vehicleNo: '',
        customVehicleNo: '', // 自定义车牌号
        quantity: 1,
        productType: '',
        province: '河南省',
        city: '',
        district: '',
        streetAddress: '',
        purchaseVoucher: '',
        qualificationCert: '',
        animalQuarantineCert: '', // 动物检疫合格证明
        meatQualityCert: '', // 肉品品质检验合格证
        appointmentDate: '', // 预约日期
        appointmentTime: '', // 预约时间
      },
      supplierList: [],
      supplierIndex: -1,
      goodsList: [],
      goodsIndex: -1,
      vehicleList: [], // 车辆列表
      vehicleIndex: -1, // 当前选中的车辆索引
      defaultVehicle: '', // 默认车辆
      showNoticePopup: false, // 控制须知弹窗显示
      productTypes: [
        {
          value: '0',
          label: '种植业产品',
          icon: 'vip',
        },
        {
          value: '1',
          label: '养殖水产品',
          icon: 'staff',
        },
        {
          value: '2',
          label: '畜牧业产品',
          icon: 'home',
        },
      ],
      provinces: [],
      provinceList: [], // 省份原始数据
      cities: [],
      cityList: [], // 城市原始数据
      districts: [],
      districtList: [], // 区县原始数据
      selectedProvince: '',
      selectedProvinceId: '',
      selectedCity: '',
      selectedCityId: '',
      selectedDistrict: '',
      selectedDistrictId: '',
    };
  },
  computed: {
    // 车辆列表（移除自定义输入选项）
    vehicleListWithInput() {
      const list = this.vehicleList.map((v) => ({
        value: v.vehiclePlate,
        label: `${v.vehiclePlate} (驾驶员:${v.driverName || ''})`.trim(),
        vehicleInfo: v,
      }));
      // 不再添加自定义输入选项，强制用户先添加车辆
      return list;
    },

    // 最小日期（明天）
    minDate() {
      const tomorrow = new Date();
      tomorrow.setDate(tomorrow.getDate() + 1); // 明天
      const year = tomorrow.getFullYear();
      const month = String(tomorrow.getMonth() + 1).padStart(2, '0');
      const day = String(tomorrow.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },

    // 最大日期（30天后）
    maxDate() {
      const now = new Date();
      now.setDate(now.getDate() + 30);
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },

    // 是否可以提交
    canSubmit() {
      return (
        this.supplierIndex > -1 &&
        this.goodsIndex > -1 &&
        this.formData.vehicleNo &&
        this.formData.quantity > 0 &&
        this.formData.productType &&
        this.formData.purchaseVoucher
      );
    },

    // 提交按钮文本
    submitButtonText() {
      // 首先检查时间选择
      if (!this.formData.appointmentDate) {
        return '请选择入场日期';
      } else if (!this.formData.appointmentTime) {
        return '请选择入场时间';
      }

      // 如果已经有添加的产品
      if (this.addedProducts.length > 0) {
        // 检查当前表单是否有内容
        const hasCurrentFormData =
          this.formData.supplierId ||
          this.formData.goodsId ||
          this.formData.vehicleNo ||
          this.formData.quantity > 1 ||
          this.formData.productType ||
          this.formData.purchaseVoucher;

        if (hasCurrentFormData) {
          return `提交预约（共${this.addedProducts.length + 1}个产品）`;
        } else {
          return `提交预约（共${this.addedProducts.length}个产品）`;
        }
      }

      // 没有添加的产品，显示当前表单的验证状态
      if (this.supplierIndex === -1) {
        return '请选择供货商';
      } else if (this.goodsIndex === -1) {
        return '请选择产品名称';
      } else if (!this.formData.vehicleNo) {
        return '请输入入场车辆';
      } else if (!this.formData.quantity || this.formData.quantity <= 0) {
        return '请输入数量';
      } else if (!this.formData.productType) {
        return '请选择产品类型';
      } else if (!this.formData.purchaseVoucher) {
        return '请上传进货凭证';
      } else {
        return '提交预约（1个产品）';
      }
    },
  },
  async onLoad() {
    // 验证用户是否是已绑定市场
    const isUserMarketValid = await this.validateUserMarket();
    if (!isUserMarketValid) {
      console.log('用户市场验证失败');
      uni.showModal({
        title: '提示',
        content: '您还未选择市场，请先选择市场后再进行预约',
        showCancel: false,
        confirmText: '去选择',
        success: (res) => {
          if (res.confirm) {
            uni.navigateTo({
              url: '/pages/mine/market/index',
            });
          }
        },
      });
      return;
    }
    console.log('用户市场验证通过');

    // 默认日期：明天
    const t = new Date(Date.now());
    // 设置预约日期为当前时间+48小时
    t.setTime(t.getTime() + 48 * 60 * 60 * 1000); // 增加48小时
    this.formData.appointmentDate = `${t.getFullYear()}-${String(t.getMonth() + 1).padStart(2, '0')}-${String(t.getDate()).padStart(2, '0')}`;
    // 设置预约时间为增加48小时后的当前时间
    this.formData.appointmentTime = `${String(t.getHours()).padStart(2, '0')}:${String(t.getMinutes()).padStart(2, '0')}`;

    // 加载供货商列表
    this.loadSuppliers();
    // 加载商品列表
    this.loadGoods();
    // 加载车辆列表
    this.loadVehicles();
    // 加载省份列表
    this.loadProvinces();
    // 设置首次加载标志为false
    this.isFirstLoad = false;
  },

  // 页面显示时重新加载数据，用于从添加页面返回时刷新列表
  onShow() {
    if (this.isFirstLoad) {
      return;
    }
    // 保存当前选择的车辆信息，防止加载列表后被覆盖
    const savedVehicleNo = this.formData.vehicleNo;
    const savedCustomVehicleNo = this.formData.customVehicleNo;
    const savedVehicleIndex = this.vehicleIndex;
    // 添加标志表示用户是否已经选择了车辆
    const hasSelectedVehicle = !!savedVehicleNo;

    // 重新加载供货商列表
    this.loadSuppliers();
    // 重新加载车辆列表 - 已修改loadVehicles方法，只有在用户未选择车辆时才设置默认车辆
    this.loadVehicles();

    this.loadGoods();

    // 恢复用户之前选择的车辆
    this.$nextTick(() => {
      // 先使用validateAndUpdateVehicleSelection验证车辆选择
      this.validateAndUpdateVehicleSelection();

      // 如果用户之前有选择车辆，手动恢复用户之前选择的车辆
      if (hasSelectedVehicle) {
        if (savedVehicleNo) {
          this.formData.vehicleNo = savedVehicleNo;
        }
        if (savedCustomVehicleNo) {
          this.formData.customVehicleNo = savedCustomVehicleNo;
        }
        if (savedVehicleIndex !== -1) {
          this.vehicleIndex = savedVehicleIndex;
        }
        // 强制更新视图，确保选择状态正确显示
        this.$forceUpdate();
      }
    });
  },
  methods: {
    // 验证用户是否是已绑定市场
    async validateUserMarket() {
      const response = await getCurrentUserMarket();
      if (response.code === 200 && response.data) {
        this.currentMarketId = response.data.deptId;
        this.currentMarketName = response.data.deptName;
      } else {
        return false;
      }
      return true;
    },

    // 日期选择
    dateChange(e) {
      const selectedDate = e.detail.value;
      const today = this.minDate;

      // 验证是否选择了过去的日期
      if (selectedDate < today) {
        uni.showToast({
          title: '不能选择过去的日期',
          icon: 'none',
          duration: 2000,
        });
        // 重置为今天
        this.formData.appointmentDate = today;
      } else {
        this.formData.appointmentDate = selectedDate;
      }
    },

    // 时间选择
    timeChange(e) {
      this.formData.appointmentTime = e.detail.value;

      // 如果选择的是今天，验证时间不能早于当前时间
      if (this.formData.appointmentDate === this.minDate) {
        const now = new Date();
        const currentTime = `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`;

        if (this.formData.appointmentTime < currentTime) {
          uni.showToast({
            title: '不能选择过去的时间',
            icon: 'none',
            duration: 2000,
          });
          // 设置为当前时间后15分钟
          now.setMinutes(now.getMinutes() + 15);
          this.formData.appointmentTime = `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`;
        }
      }
    },

    // 加载供货商列表
    async loadSuppliers() {
      try {
        const response = await mySupplierList();
        console.log('供货商列表响应:', response);
        if (response.code === 200) {
          // 统一取 rows 或 data，确保为数组
          const suppliers = Array.isArray(response.rows) ? response.rows : Array.isArray(response.data) ? response.data : [];
          this.supplierList = suppliers;
        } else {
          console.error('加载供货商失败，响应码:', response.code, response.msg);
          this.supplierList = [];
        }
      } catch (error) {
        console.error('加载供货商失败，详细错误:', error);
        this.supplierList = [];
        const code = error.statusCode || error.data?.code;
        const msg = code === 403 ? '无权限访问供货商' : code === 401 ? '请先登录' : '网络请求失败';
        uni.showToast({ title: msg, icon: 'none', duration: 2000 });
      }
    },

    // 加载商品列表
    async loadGoods() {
      try {
        const { myGoodsList } = await import('@/api/business/goods.js');
        const response = await myGoodsList();
        if (response.code === 200) {
          this.goodsList = response.data || [];
        }
      } catch (error) {
        this.goodsList = [];
      }
    },

    // 根据供货商加载关联的商品
    async loadGoodsBySupplierbak(supplierId) {
      if (!supplierId) {
        this.goodsList = [];
        return;
      }

      try {
        uni.showLoading({
          title: '加载商品中...',
        });
        const { getGoodsBySupplier } = await import('@/api/system/supplierGoods.js');
        const response = await getGoodsBySupplier(supplierId);
        uni.hideLoading();

        if (response.code === 200) {
          this.goodsList = response.data || [];
          if (this.goodsList.length === 0) {
            uni.showToast({
              title: '该供货商暂无关联产品，请您先添加产品后到个人中心供货商商品配置进行绑定',
              icon: 'none',
              duration: 7000,
            });
          }
        }
      } catch (error) {
        uni.hideLoading();
        console.error('加载供货商商品失败:', error);
        this.goodsList = [];
        uni.showToast({
          title: '加载商品失败，请检查网络',
          icon: 'none',
          duration: 2000,
        });
      }
    },

    // 供货商选择
    supplierChange(e) {
      this.supplierIndex = e.detail.value;
      const supplier = this.supplierList[this.supplierIndex];
      if (supplier) {
        this.formData.supplierId = supplier.supplierId;
        // 清空已选择的商品
      }
    },

    // 商品选择
    goodsChange(e) {
      this.goodsIndex = e.detail.value;
      console.log('商品选择:', this.goodsList[this.goodsIndex]);
      this.formData.goodsId = this.goodsList[this.goodsIndex]?.goodsId;
      this.formData.productType = this.goodsList[this.goodsIndex]?.goodsCategory;
    },

    // 加载商户信息
    async loadMerchantInfo() {
      try {
        const response = await getCurrentMerchantInfo();
        if (response.code === 200 && response.data) {
          // 商户信息加载成功
        }
      } catch (error) {
        console.error('加载商户信息失败:', error);
      }
    },

    // 加载车辆列表
    async loadVehicles() {
      try {
        const { getVehicleList } = await import('@/api/system/vehicle.js');
        const response = await getVehicleList();

        if (response.code === 200) {
          this.vehicleList = response.data || [];
          // 查找并设置默认车辆
          const defaultVehicle = this.vehicleList.find((v) => v.isDefault === '1' || v.is_default === '1');
          if (defaultVehicle) {
            const vehiclePlate = defaultVehicle.vehiclePlate || defaultVehicle.vehicle_plate;
            this.defaultVehicle = vehiclePlate;

            // 只有在用户没有选择车辆时才设置默认车辆
            if (!this.formData.vehicleNo) {
              this.formData.vehicleNo = vehiclePlate;
              // 找到默认车辆在列表中的索引
              this.vehicleIndex = this.vehicleListWithInput.findIndex((v) => v.value === vehiclePlate);
            }
          }
        }
      } catch (error) {
        console.error('加载车辆列表失败:', error);
        this.vehicleList = [];
      }
    },

    // 使用默认车辆
    useDefaultVehicle() {
      if (this.defaultVehicle) {
        this.formData.vehicleNo = this.defaultVehicle;
        uni.showToast({
          title: '已使用默认车辆',
          icon: 'success',
        });
      }
    },

    // 车辆输入
    onVehicleInput(e) {
      this.formData.vehicleNo = e.detail.value.toUpperCase();
    },

    // 数量控制
    decreaseQuantity() {
      if (this.formData.quantity > 1) {
        this.formData.quantity--;
      }
    },

    increaseQuantity() {
      this.formData.quantity++;
    },

    // 选择产品类型
    selectProductType(value) {
      console.log('产品类型:', value);
      this.formData.productType = value;
    },

    // 地址选择
    onProvinceChange(e) {
      const index = e.detail.value;
      const province = this.provinceList[index];
      if (province) {
        this.selectedProvince = province.regionName;
        this.selectedProvinceId = province.id;
        this.formData.province = province.regionName;
        // 清空市区选择
        this.selectedCity = '';
        this.selectedCityId = '';
        this.selectedDistrict = '';
        this.selectedDistrictId = '';
        this.formData.city = '';
        this.formData.district = '';
        this.cities = [];
        this.districts = [];
        // 加载城市数据
        this.loadCities(province.id);
      }
    },

    onCityChange(e) {
      const index = e.detail.value;
      const city = this.cityList[index];
      if (city) {
        this.selectedCity = city.regionName;
        this.selectedCityId = city.id;
        this.formData.city = city.regionName;
        // 清空区县选择
        this.selectedDistrict = '';
        this.selectedDistrictId = '';
        this.formData.district = '';
        this.districts = [];
        // 加载区县数据
        this.loadDistricts(city.id);
      }
    },

    onDistrictChange(e) {
      const index = e.detail.value;
      const district = this.districtList[index];
      if (district) {
        this.selectedDistrict = district.regionName;
        this.selectedDistrictId = district.id;
        this.formData.district = district.regionName;
      }
    },

    // 加载省份数据
    async loadProvinces() {
      try {
        const response = await getProvinces();
        if (response.code === 200 && response.data) {
          this.provinceList = response.data;
          this.provinces = response.data.map((item) => item.regionName);

          // 如果有默认省份，自动加载对应的城市
          if (this.selectedProvince) {
            const defaultProvince = this.provinceList.find((p) => p.regionName === this.selectedProvince);
            if (defaultProvince) {
              this.selectedProvinceId = defaultProvince.id;
              // 加载默认省份的城市列表
              await this.loadCities(defaultProvince.id);
            }
          }
        }
      } catch (error) {
        console.error('加载省份失败:', error);
      }
    },

    // 加载城市数据
    async loadCities(provinceId) {
      try {
        const response = await getCitiesByProvinceId(provinceId);
        if (response.code === 200 && response.data) {
          this.cityList = response.data;
          this.cities = response.data.map((item) => item.regionName);

          // 不设置默认城市
        }
      } catch (error) {
        console.error('加载城市失败:', error);
      }
    },

    // 加载区县数据
    async loadDistricts(cityId) {
      try {
        const response = await getDistrictsByCityId(cityId);
        if (response.code === 200 && response.data) {
          this.districtList = response.data;
          this.districts = response.data.map((item) => item.regionName);

          // 不设置默认区县
        }
      } catch (error) {
        console.error('加载区县失败:', error);
      }
    },

    // 处理进货凭证上传
    handlePurchaseVoucherUpload(url) {
      this.formData.purchaseVoucher = url;
    },

    // 处理动物检疫合格证明上传
    handleAnimalQuarantineCertUpload(url) {
      this.formData.animalQuarantineCert = url;
    },

    // 处理肉品品质检验合格证上传
    handleMeatQualityCertUpload(url) {
      this.formData.meatQualityCert = url;
    },

    // 处理承诺达标合格证上传
    handleQualificationCertUpload(url) {
      this.formData.qualificationCert = url;
    },

    // 更新产品供货商
    updateProductSupplier(index, e) {
      const selectedIndex = e.detail.value;
      const supplier = this.supplierList[selectedIndex];
      if (supplier) {
        this.$set(this.addedProducts[index], 'supplierIndex', selectedIndex);
        this.$set(this.addedProducts[index], 'supplierId', supplier.supplierId);
        this.$set(this.addedProducts[index], 'supplierName', supplier.supplierName);

        // 重新加载该供货商的商品列表
        this.loadGoodsForProduct(index, supplier.supplierId);
      }
    },

    // 为特定产品加载商品列表
    async loadGoodsForProduct(productIndex, supplierId) {
      try {
        const res = await this.$http.get(`/system/supplier/goods/${supplierId}`);
        if (res.code === 200 && res.data) {
          this.$set(this.addedProducts[productIndex], 'goodsListForProduct', res.data);
        }
      } catch (error) {
        console.error('加载商品列表失败:', error);
      }
    },

    // 更新产品商品
    updateProductGoods(index, e) {
      const selectedIndex = e.detail.value;
      const goodsList = this.addedProducts[index].goodsListForProduct || [];
      const goods = goodsList[selectedIndex];
      if (goods) {
        this.$set(this.addedProducts[index], 'goodsIndex', selectedIndex);
        this.$set(this.addedProducts[index], 'goodsId', goods.goodsId);
        this.$set(this.addedProducts[index], 'goodsName', goods.goodsName);
      }
    },

    // 更新产品字段
    updateProductField(index, field, value) {
      this.$set(this.addedProducts[index], field, value);

      // 如果更新的是产品类型，同时更新类型名称
      if (field === 'productType') {
        const type = this.productTypes.find((t) => t.value === value);
        if (type) {
          this.$set(this.addedProducts[index], 'productTypeName', type.label);
        }
      }
    },

    // 更新产品车辆
    updateProductVehicle(index, e) {
      const selectedIndex = e.detail.value;
      const selectedOption = this.vehicleListWithInput[selectedIndex];

      if (selectedOption) {
        // 用户选择了具体的车辆
        this.$set(this.addedProducts[index], 'vehicleNo', selectedOption.value);
        this.$set(this.addedProducts[index], 'vehicleIndex', selectedIndex);
      }
    },

    // 处理自定义车辆输入失去焦点
    handleCustomVehicleBlur(index, e) {
      const value = e.detail.value;
      if (value) {
        // 如果输入了值，保存到vehicleNo
        this.$set(this.addedProducts[index], 'vehicleNo', value);
      } else {
        // 如果没有输入值，恢复到选择状态
        this.$set(this.addedProducts[index], 'vehicleNo', '');
        this.$set(this.addedProducts[index], 'customVehicleNo', '');
      }
    },

    // 查找车辆在列表中的索引
    findVehicleIndex(vehiclePlate) {
      if (!vehiclePlate) return 0;
      console.log('当前车辆信息：', this.vehicleListWithInput);
      const index = this.vehicleListWithInput.findIndex((v) => v.value === vehiclePlate);
      return index >= 0 ? index : 0; // 如果找不到，默认选择第一个
    },

    // 验证并更新车辆选择状态
    validateAndUpdateVehicleSelection() {
      // 验证当前选择的车辆是否还在列表中
      if (this.formData.vehicleNo) {
        const vehicleIndex = this.findVehicleIndex(this.formData.vehicleNo);
        if (vehicleIndex >= 0 && vehicleIndex < this.vehicleListWithInput.length) {
          this.vehicleIndex = vehicleIndex;
        } else {
          // 车辆不在列表中，重置为默认车辆
          this.formData.vehicleNo = this.defaultVehicle || '';
          this.vehicleIndex = this.findVehicleIndex(this.formData.vehicleNo);
        }
      }
    },

    // 处理主表单车辆选择
    handleVehicleChange(e) {
      const selectedIndex = e.detail.value;
      this.vehicleIndex = selectedIndex;
      const selectedOption = this.vehicleListWithInput[selectedIndex];

      if (selectedOption) {
        // 用户选择了具体的车辆
        this.formData.vehicleNo = selectedOption.value;
      }
    },

    // 处理主表单自定义车辆输入失焦
    handleMainVehicleBlur() {
      if (this.formData.customVehicleNo) {
        // 如果输入了值，保存到vehicleNo
        this.formData.vehicleNo = this.formData.customVehicleNo;
      } else {
        // 如果没有输入值，恢复到选择状态
        this.formData.vehicleNo = '';
        this.formData.customVehicleNo = '';
        this.vehicleIndex = -1;
      }
    },

    // 更新产品数量
    updateProductQuantity(index, delta) {
      const currentQuantity = parseFloat(this.addedProducts[index].quantity) || 0;
      const newQuantity = Math.max(0.1, currentQuantity + delta);
      this.$set(this.addedProducts[index], 'quantity', newQuantity);
    },

    // 保存产品（收起编辑）
    saveProduct(index) {
      // 验证必填字段
      const product = this.addedProducts[index];
      if (!product.supplierId || !product.goodsId || !product.vehicleNo || !product.quantity) {
        uni.showToast({
          title: '请填写完整信息',
          icon: 'none',
        });
        return;
      }
      if (!product.purchaseVoucher) {
        uni.showToast({
          title: '请上传进货凭证',
          icon: 'none',
        });
        return;
      }

      // 更新完整地址
      const fullAddress = [product.province || '河南省', product.city, product.district, product.streetAddress].filter(Boolean).join('');
      this.$set(this.addedProducts[index], 'fullAddress', fullAddress);

      // 收起编辑状态
      this.$set(this.expandedProducts, index, false);
      uni.showToast({
        title: '保存成功',
        icon: 'success',
      });
    },

    // 更新产品的进货凭证
    uploadProductPurchaseVoucher(index, url) {
      console.log('更新进货凭证', index, url);
      this.$set(this.addedProducts[index], 'purchaseVoucher', url);
    },

    // 更新产品的合格证
    uploadProductQualificationCert(index, url) {
      console.log('更新合格证', index, url);
      this.$set(this.addedProducts[index], 'qualificationCert', url);
    },

    // 更新产品的动物检疫合格证明
    uploadProductAnimalQuarantineCert(index, url) {
      console.log('更新动物检疫合格证明', index, url);
      this.$set(this.addedProducts[index], 'animalQuarantineCert', url);
    },

    // 更新产品的肉品品质检验合格证
    uploadProductMeatQualityCert(index, url) {
      console.log('更新肉品品质检验合格证', index, url);
      this.$set(this.addedProducts[index], 'meatQualityCert', url);
    },

    // 上传产品的肉品品质检验合格证
    // uploadProductMeatQualityCert(index) {
    //   uni.chooseImage({
    //     count: 1,
    //     sizeType: ['compressed'],
    //     sourceType: ['camera', 'album'],
    //     success: (res) => {
    //       const tempFilePath = res.tempFilePaths[0];
    //       uni.showLoading({
    //         title: '上传中...',
    //       });

    //       upload({
    //         url: '/common/upload',
    //         filePath: tempFilePath,
    //         name: 'file',
    //         timeout: 60000, // 设置60秒超时时间
    //         formData: {
    //           type: 'meatQualityCert',
    //           storageType: 'local',
    //         },
    //       })
    //         .then((response) => {
    //           uni.hideLoading();
    //           if (response && response.code === 200) {
    //             let imageUrl = response.url || response.fileName;
    //             if (!isHttp(imageUrl)) {
    //               imageUrl = baseUrl + imageUrl;
    //             }
    //             this.$set(this.addedProducts[index], 'meatQualityCert', imageUrl);
    //             uni.showToast({
    //               title: '上传成功',
    //               icon: 'success',
    //             });
    //           } else {
    //             uni.showToast({
    //               title: response?.msg || '上传失败',
    //               icon: 'none',
    //             });
    //           }
    //         })
    //         .catch((error) => {
    //           uni.hideLoading();
    //           uni.showToast({
    //             title: typeof error === 'string' ? error : '网络错误',
    //             icon: 'none',
    //           });
    //         });
    //     },
    //   });
    // },

    // 预览产品的进货凭证
    previewProductVoucher(index) {
      const product = this.addedProducts[index];
      if (product.purchaseVoucher) {
        uni.previewImage({
          urls: [product.purchaseVoucher],
          current: 0,
        });
      }
    },

    // 预览产品的合格证
    previewProductCert(index) {
      const product = this.addedProducts[index];
      if (product.qualificationCert) {
        uni.previewImage({
          urls: [product.qualificationCert],
          current: 0,
        });
      }
    },

    // 预览产品的肉品品质检验合格证
    previewProductMeatQualityCert(index) {
      const product = this.addedProducts[index];
      if (product.meatQualityCert) {
        uni.previewImage({
          urls: [product.meatQualityCert],
          current: 0,
        });
      }
    },

    // 预览产品的动物检疫合格证明
    previewProductAnimalQuarantineCert(index) {
      const product = this.addedProducts[index];
      if (product.animalQuarantineCert) {
        uni.previewImage({
          urls: [product.animalQuarantineCert],
          current: 0,
        });
      }
    },

    // 添加产品
    addProduct() {
      if (!this.validateForm()) return;

      // 获取产品类型名称
      const productType = this.productTypes.find((t) => t.value === this.formData.productType);
      const productTypeName = productType ? productType.label : '';

      // 确保产地信息正确
      const provinceValue = this.selectedProvince || this.formData.province || '河南省';
      const cityValue = this.selectedCity || this.formData.city || '';
      const districtValue = this.selectedDistrict || this.formData.district || '';
      const streetValue = this.formData.streetAddress || '';

      // 重新构建完整地址
      const completeAddress = [provinceValue, cityValue, districtValue, streetValue].filter(Boolean).join('');

      // 添加产品到列表
      const finalVehicleNo = this.formData.vehicleNo === 'custom' ? this.formData.customVehicleNo : this.formData.vehicleNo;
      const newProduct = {
        supplierId: this.formData.supplierId,
        supplierName: this.supplierList[this.supplierIndex]?.supplierName || '',
        supplierIndex: this.supplierIndex,
        goodsId: this.formData.goodsId,
        goodsName: this.goodsList[this.goodsIndex]?.goodsName || '',
        goodsIndex: this.goodsIndex,
        goodsListForProduct: [...this.goodsList], // 保存当前商品列表供编辑使用
        vehicleNo: finalVehicleNo,
        vehicleIndex: this.vehicleIndex,
        customVehicleNo: this.formData.customVehicleNo || '',
        quantity: this.formData.quantity,
        productType: this.formData.productType,
        productTypeName: productTypeName,
        province: provinceValue,
        city: cityValue,
        district: districtValue,
        streetAddress: streetValue,
        fullAddress: completeAddress,
        originPlace: completeAddress, // 添加originPlace字段
        purchaseVoucher: this.formData.purchaseVoucher,
        qualificationCert: this.formData.qualificationCert,
        animalQuarantineCert: this.formData.animalQuarantineCert,
        meatQualityCert: this.formData.meatQualityCert,
      };

      console.log('添加产品时的产地信息:', {
        province: newProduct.province,
        city: newProduct.city,
        district: newProduct.district,
        originPlace: newProduct.originPlace,
      });

      console.log('添加的产品信息:', newProduct);

      this.addedProducts.push(newProduct);
      // 使用 Vue.set 确保响应式
      this.$set(this.expandedProducts, this.addedProducts.length - 1, false); // 默认收起

      uni.showToast({
        title: '产品添加成功',
        icon: 'success',
      });
      this.resetFormForNext();
    },

    // 切换产品展开/收起
    toggleProductExpand(index) {
      console.log('点击展开/收起，索引:', index, '当前状态:', this.expandedProducts[index]);
      // 确保响应式更新
      const currentState = this.expandedProducts[index] || false;
      this.$set(this.expandedProducts, index, !currentState);
      console.log('更新后状态:', this.expandedProducts[index]);
    },

    // 移除产品
    removeProduct(index) {
      uni.showModal({
        title: '确认删除',
        content: '确定要删除这个产品吗？',
        success: (res) => {
          if (res.confirm) {
            this.addedProducts.splice(index, 1);
            // 重新整理展开状态
            const newExpanded = {};
            for (let i = 0; i < this.addedProducts.length; i++) {
              newExpanded[i] = this.expandedProducts[i] || false;
            }
            this.expandedProducts = newExpanded;
            uni.showToast({
              title: '删除成功',
              icon: 'success',
            });
          }
        },
      });
    },

    /**
     * 重置表单以便添加下一个产品
     * 保留用户已选择的时间和车辆信息，重置其他表单数据
     */
    resetFormForNext() {
      // 保存用户已选择的预约日期和时间
      const savedDate = this.formData.appointmentDate;
      const savedTime = this.formData.appointmentTime;

      // 保存用户当前选择的车辆信息
      const savedVehicleNo = this.formData.vehicleNo; // 保存当前选择的车辆编号
      const savedCustomVehicleNo = this.formData.customVehicleNo; // 保存自定义车辆号
      const savedVehicleIndex = this.vehicleIndex; // 保存车辆选择索引

      // 重置供货商和商品选择索引，准备选择新的供货商和商品
      this.supplierIndex = -1;
      this.goodsIndex = -1;
      // 保持车辆选择索引不变，实现添加新产品时不重置车辆选择
      this.vehicleIndex = savedVehicleIndex;

      // 清空表单数据，准备添加新产品
      this.formData = {
        supplierId: '', // 重置供货商ID
        goodsId: '', // 重置商品ID
        vehicleNo: savedVehicleNo, // 保留之前选择的车辆
        customVehicleNo: savedCustomVehicleNo, // 保留自定义车辆号
        quantity: 1, // 默认数量为1
        productType: '', // 重置产品类型
        province: '河南省', // 默认省份
        city: '', // 重置城市
        district: '', // 重置区县
        streetAddress: '', // 重置街道地址
        purchaseVoucher: '', // 重置采购凭证
        qualificationCert: '', // 重置资质证书
        animalQuarantineCert: '', // 重置动物检疫合格证明
        meatQualityCert: '', // 重置肉品品质检验合格证
        appointmentDate: savedDate, // 保留预约日期
        appointmentTime: savedTime, // 保留预约时间
      };

      // 清空商品列表，以便重新选择供货商后加载新的商品列表
      // this.goodsList = [];

      // 重置地址选择相关变量
      this.selectedProvince = '';
      this.selectedCity = '';
      this.selectedDistrict = '';
    },

    // 验证表单
    validateForm() {
      if (!this.formData.supplierId) {
        uni.showToast({
          title: '请选择供货商',
          icon: 'none',
        });
        return false;
      }
      if (!this.formData.goodsId) {
        uni.showToast({
          title: '请选择产品名称',
          icon: 'none',
        });
        return false;
      }
      const finalVehicleNo = this.formData.vehicleNo === 'custom' ? this.formData.customVehicleNo : this.formData.vehicleNo;
      if (!finalVehicleNo) {
        uni.showToast({
          title: '请选择或输入入场车辆',
          icon: 'none',
        });
        return false;
      }
      if (!this.formData.productType) {
        uni.showToast({
          title: '请选择产品类型',
          icon: 'none',
        });
        return false;
      }
      if (!this.formData.purchaseVoucher) {
        uni.showToast({
          title: '请上传进货凭证',
          icon: 'none',
        });
        return false;
      }
      // 畜牧业产品必须上传额外证明
      if (this.formData.productType === '2') {
        if (!this.formData.animalQuarantineCert) {
          uni.showToast({
            title: '请上传动物检疫合格证明',
            icon: 'none',
          });
          return false;
        }
        if (!this.formData.meatQualityCert) {
          uni.showToast({
            title: '请上传肉品品质检验合格证',
            icon: 'none',
          });
          return false;
        }
      }
      return true;
    },

    // 重置表单
    resetForm() {
      this.supplierIndex = -1;
      this.goodsIndex = -1;
      this.formData = {
        ...this.formData,
        supplierId: '',
        goodsId: '',
        vehicleNo: this.defaultVehicle || '', // 保留默认车辆
        quantity: 1,
        productType: '',
        purchaseVoucher: '',
        qualificationCert: '',
        animalQuarantineCert: '',
        meatQualityCert: '',
      };
    },

    // 提交表单
    async submitForm() {
      // 保存日期和时间（在任何操作之前）
      const savedDate = this.formData.appointmentDate;
      const savedTime = this.formData.appointmentTime;

      // 检查是否选择了时间（提前检查）
      if (!savedDate) {
        uni.showToast({
          title: '请选择入场日期',
          icon: 'none',
        });
        return;
      }
      if (!savedTime) {
        uni.showToast({
          title: '请选择入场时间',
          icon: 'none',
        });
        return;
      }

      // 检查当前表单是否有内容需要添加
      const hasCurrentFormData =
        this.formData.supplierId &&
        this.formData.goodsId &&
        this.formData.vehicleNo &&
        this.formData.quantity > 0 &&
        this.formData.productType &&
        this.formData.purchaseVoucher;

      console.log('检查当前表单:', {
        supplierId: this.formData.supplierId,
        goodsId: this.formData.goodsId,
        vehicleNo: this.formData.vehicleNo,
        quantity: this.formData.quantity,
        productType: this.formData.productType,
        purchaseVoucher: this.formData.purchaseVoucher,
        hasCurrentFormData: hasCurrentFormData,
        appointmentDate: savedDate,
        appointmentTime: savedTime,
      });

      if (hasCurrentFormData) {
        console.log('当前表单有内容，准备添加到产品列表');
        // 如果当前表单有内容，先验证并添加
        if (this.validateForm()) {
          console.log('验证表单成功，准备添加产品');
          this.addProduct();
          console.log('产品已添加，当前产品数:', this.addedProducts.length);
        } else {
          return;
        }
      } else {
        // 检查是否有部分填写的表单
        const hasPartialFormData =
          this.formData.supplierId ||
          this.formData.goodsId ||
          (this.formData.vehicleNo && this.formData.vehicleNo !== this.defaultVehicle) ||
          this.formData.quantity > 1 ||
          this.formData.productType;

        if (hasPartialFormData) {
          console.log('当前表单有部分内容但不完整');
          // 使用 Promise 包装异步操作
          const shouldContinue = await new Promise((resolve) => {
            uni.showModal({
              title: '提示',
              content: '当前表单尚未完成，是否只提交已添加的产品？',
              success: (res) => {
                resolve(res.confirm);
              },
            });
          });

          if (!shouldContinue) {
            return;
          }
        }
      }

      // 确保日期时间没有丢失（使用保存的值）
      if (!this.formData.appointmentDate) {
        this.formData.appointmentDate = savedDate;
      }
      if (!this.formData.appointmentTime) {
        this.formData.appointmentTime = savedTime;
      }

      // 检查是否有产品（包括刚添加的）
      if (this.addedProducts.length === 0) {
        uni.showToast({
          title: '请至少添加一个产品',
          icon: 'none',
        });
        return;
      }

      console.log('准备提交产品数量:', this.addedProducts.length);
      console.log(
        '产品列表:',
        this.addedProducts.map((p) => p.goodsName)
      );
      console.log('预约时间:', this.formData.appointmentDate, this.formData.appointmentTime);

      uni.showLoading({
        title: '提交中...',
      });

      try {
        // 获取商户ID - 确保是数字类型
        let merchantId = uni.getStorageSync('merchantId');
        if (!merchantId) {
          // 如果没有商户ID，先获取并存储
          const merchantInfo = await getCurrentMerchantInfo();
          if (merchantInfo.code === 200 && merchantInfo.data) {
            merchantId = merchantInfo.data.merchantId;
            uni.setStorageSync('merchantId', merchantId);
          } else {
            // 暂时允许无商户提交，使用默认商户ID
            merchantId = 13; // 使用测试商户ID
            console.log('无商户信息，使用默认商户ID:', merchantId);
          }
        }

        // 确保merchantId是有效的数字
        merchantId = parseInt(merchantId);
        if (isNaN(merchantId) || merchantId <= 0) {
          // 如果解析失败，使用默认商户ID
          merchantId = 13;
          console.log('merchantId解析失败，使用默认商户ID:', merchantId);
        }

        // 使用保存的日期和时间（避免被重置）
        const appointmentDate = savedDate || this.formData.appointmentDate;
        const appointmentTime = savedTime || this.formData.appointmentTime;

        // 构建完整地址
        const originPlace = [
          this.addedProducts[0].province,
          this.addedProducts[0].city,
          this.addedProducts[0].district,
          this.addedProducts[0].streetAddress,
        ]
          .filter(Boolean)
          .join('');

        // 使用从服务器获取的市场ID
        const marketId = this.currentMarketId;

        // 构建提交数据 - 适配后端MiniAppointmentDTO结构
        const submitData = {
          appointmentType: '2', // 2-食用农产品预约
          merchantId: parseInt(merchantId),
          deptId: marketId ? parseInt(marketId) : null, // 添加市场ID
          appointmentDate: appointmentDate,
          appointmentTime: appointmentTime,
          goodsList: this.addedProducts.map((product) => ({
            goodsId: product.goodsId,
            goodsName: product.goodsName || '',
            quantity: parseFloat(product.quantity),
            unit: 'kg',
            vehicleNo: product.vehicleNo || '',
            purchaseVoucher: product.purchaseVoucher || '',
            qualificationCert: product.qualificationCert || '',
            animalQuarantineCert: product.animalQuarantineCert || '',
            meatQualityCert: product.meatQualityCert || '',
            originPlace: product.originPlace || '', // 添加产地信息
          })),
          // 取第一个产品的信息作为主要信息
          supplierId: this.addedProducts[0].supplierId,
          vehicleNo: this.addedProducts[0].vehicleNo || '', // 确保不为null
          productType: this.addedProducts[0].productType,
          province: this.addedProducts[0].province,
          city: this.addedProducts[0].city,
          district: this.addedProducts[0].district,
          originPlace: originPlace, // 添加完整产地信息
          purchaseVoucher: this.addedProducts[0].purchaseVoucher,
          qualificationCert: this.addedProducts[0].qualificationCert,
          animalQuarantineCert: this.addedProducts[0].animalQuarantineCert,
          meatQualityCert: this.addedProducts[0].meatQualityCert,
        };

        // 打印提交数据，便于调试
        console.log('提交的预约数据:', submitData);
        console.log('车牌号:', submitData.vehicleNo);
        console.log('产地信息:', submitData.originPlace);
        console.log('省市区:', submitData.province, submitData.city, submitData.district);
        console.log(
          '商品列表产地:',
          submitData.goodsList.map((g) => g.originPlace)
        );

        // 调用提交接口
        const response = await submitAppointment(submitData);
        uni.hideLoading();

        if (response.code === 200) {
          uni.showToast({
            title: '预约申请已提交',
            icon: 'success',
            duration: 2000,
          });

          setTimeout(() => {
            uni.redirectTo({
              url: '/pages/appointment/record',
            });
          }, 1500);
        } else {
          uni.showToast({
            title: response.msg || '提交失败',
            icon: 'none',
            duration: 2000,
          });
        }
      } catch (error) {
        uni.hideLoading();
        console.error('提交预约失败:', error);
        uni.showToast({
          title: '提交失败，请稍后重试',
          icon: 'none',
          duration: 2000,
        });
      }
    },

    // 添加供货商
    addSupplier() {
      uni.navigateTo({
        url: '/pages/supplier/add',
      });
    },

    // 添加商品
    addGoods() {
      uni.navigateTo({
        url: '/pages/goods/add',
      });
    },

    // 添加车辆
    addVehicle() {
      uni.navigateTo({
        url: '/pages/vehicle/add',
      });
    },

    // 显示预约须知
    showNotice() {
      this.showNoticePopup = true;
    },

    hideNotice() {
      this.showNoticePopup = false;
    },
  },
};
</script>

<style scoped>
.appointment-food {
  background: linear-gradient(180deg, #f0f7ff 0%, #f8fbff 100%);
  min-height: 100vh;
  padding-top: 1rpx;
}

/* 表单容器 */
.form-container {
  background-color: #fff;
  margin: 20rpx;
  border-radius: 20rpx;
  padding: 32rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
  border: 1rpx solid rgba(255, 255, 255, 0.8);
}

/* 须知提示横幅 */
.notice-banner {
  background: linear-gradient(135deg, #fff9e6 0%, #fff3cd 100%);
  border-radius: 12rpx;
  padding: 20rpx 24rpx;
  margin-bottom: 30rpx;
  border: 1rpx solid #ffd591;
  box-shadow: 0 2rpx 8rpx rgba(255, 152, 0, 0.1);
}

.notice-banner-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.notice-banner-text {
  flex: 1;
  color: #ff9800;
  font-size: 28rpx;
  font-weight: 500;
  margin: 0 16rpx;
}

/* 时间选择区域 */
.time-section {
  margin-bottom: 30rpx;
  padding-bottom: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

/* 车辆选择区域 */
.vehicle-section {
  margin-bottom: 30rpx;
  padding-bottom: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.vehicle-selector-wrapper {
  margin-top: 20rpx;
}

.vehicle-selector-wrapper .picker {
  width: 100%;
  height: 80rpx;
  background-color: #f8f8f8;
  border-radius: 12rpx;
  padding: 0 24rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.vehicle-selector-wrapper .picker-text {
  font-size: 30rpx;
  color: #333;
  flex: 1;
}

.vehicle-selector-wrapper .vehicle-input {
  width: 100%;
  height: 80rpx;
  background-color: #fff;
  border: 2rpx solid #1890ff;
  border-radius: 12rpx;
  padding: 0 24rpx;
  font-size: 30rpx;
  color: #333;
  text-transform: uppercase;
}

.vehicle-tip {
  display: block;
  margin-top: 10rpx;
  font-size: 24rpx;
  color: #1890ff;
}

.time-selector {
  display: flex;
  gap: 20rpx;
  margin-top: 20rpx;
}

.time-item {
  flex: 1;
}

.time-label {
  font-size: 26rpx;
  color: #666;
  margin-bottom: 10rpx;
  display: block;
}

.time-picker {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 24rpx 20rpx;
  background-color: #fff;
  border-radius: 12rpx;
  border: 1rpx solid #e6e6e6;
  margin-top: 10rpx;
  height: 88rpx;
  box-sizing: border-box;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);
  transition: all 0.3s ease;
}

.time-picker:active {
  background-color: #f8f9fa;
  border-color: #1890ff;
  transform: scale(0.98);
  box-shadow: 0 2rpx 12rpx rgba(24, 144, 255, 0.15);
}

.time-value {
  font-size: 30rpx;
  color: #333;
  line-height: 40rpx;
  font-weight: 500;
}

.time-value:empty::before {
  content: attr(placeholder);
  color: #999;
  font-weight: normal;
}

.time-tip {
  font-size: 24rpx;
  color: #ff6b6b;
  margin-top: 15rpx;
  display: block;
}

/* 提示区域 */
.tip-area {
  background: linear-gradient(135deg, #e6f7ff 0%, #f0f9ff 100%);
  padding: 24rpx 28rpx;
  margin-bottom: 30rpx;
  border-radius: 12rpx;
  border-left: 4rpx solid #1890ff;
  box-shadow: 0 2rpx 8rpx rgba(24, 144, 255, 0.08);
}

.tip-text {
  color: #1890ff;
  font-size: 28rpx;
}

/* 表单行 */
.form-row {
  display: flex;
  align-items: center;
  padding: 25rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.form-row:last-child {
  border-bottom: none;
}

.label {
  width: 160rpx;
  font-size: 30rpx;
  color: #333;
}

.picker {
  flex: 1;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 24rpx;
  background-color: #fff;
  border-radius: 12rpx;
  border: 1rpx solid #e6e6e6;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);
  transition: all 0.2s;
}

.picker:active {
  background-color: #f8f8f8;
  border-color: #1890ff;
}

/* 选择器和添加按钮组合布局 */
.picker-with-add {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 12rpx;
}

.picker-main {
  flex: 1;
}

.add-btn {
  width: 60rpx;
  height: 60rpx;
  background: linear-gradient(135deg, #e6f7ff 0%, #f0f9ff 100%);
  border: 1rpx solid #1890ff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2rpx 8rpx rgba(24, 144, 255, 0.1);
  transition: all 0.2s;
  flex-shrink: 0;
}

.add-btn:active {
  background: linear-gradient(135deg, #1890ff 0%, #40a9ff 100%);
  transform: scale(0.95);
  box-shadow: 0 1rpx 4rpx rgba(24, 144, 255, 0.2);
}

.add-btn:active uni-icons {
  color: #fff !important;
}

.picker-text {
  font-size: 28rpx;
  color: #666;
}

/* 数量控制 */
.quantity-control {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.quantity-btn {
  width: 60rpx;
  height: 60rpx;
  background-color: #fff;
  border: 1rpx solid #e6e6e6;
  border-radius: 50%;
  font-size: 32rpx;
  color: #666;
  display: flex;
  align-items: center;
  justify-content: center;
  line-height: 1;
  padding: 0;
  box-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.06);
  transition: all 0.2s;
}

.quantity-btn:active {
  background-color: #1890ff;
  color: #fff;
  border-color: #1890ff;
}

.quantity-input {
  width: 100rpx;
  height: 60rpx;
  text-align: center;
  font-size: 32rpx;
  color: #333;
  margin: 0 20rpx;
  border: none;
}

/* 车辆输入 */
.vehicle-input-wrapper {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.vehicle-selector {
  flex: 1;
  display: flex;
  align-items: center;
}

/* 车辆选择器特殊样式 */
.vehicle-selector .picker-with-add {
  width: 100%;
}

.vehicle-selector .picker {
  background-color: #f8f8f8;
  border: 1rpx solid #e6e6e6;
  height: 80rpx;
}

.vehicle-input {
  flex: 1;
  height: 70rpx;
  padding: 0 24rpx;
  background-color: #fff;
  border: 1rpx solid #e6e6e6;
  border-radius: 12rpx;
  font-size: 30rpx;
  color: #333;
  text-transform: uppercase;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);
  transition: all 0.2s;
}

.vehicle-input:focus {
  border-color: #1890ff;
  box-shadow: 0 2rpx 12rpx rgba(24, 144, 255, 0.15);
}

.vehicle-default-btn {
  padding: 15rpx 25rpx;
  background-color: #e6f7ff;
  border: 2rpx solid #1890ff;
  border-radius: 8rpx;
}

.default-btn-text {
  font-size: 26rpx;
  color: #1890ff;
}

/* 区块区域 */
.section-area {
  margin-top: 30rpx;
  padding-top: 30rpx;
  border-top: 1rpx solid #f0f0f0;
}

.section-title {
  font-size: 30rpx;
  color: #333;
  margin-bottom: 20rpx;
  display: block;
}

.section-title.required::before {
  content: '*';
  color: #ff4d4f;
  margin-right: 8rpx;
}

/* 产品类型 */
.product-types {
  display: flex;
  gap: 20rpx;
}

.type-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 30rpx 0;
  border: 1rpx solid #e6e6e6;
  border-radius: 16rpx;
  background-color: #fff;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);
  transition: all 0.2s;
}

.type-item.active {
  border-color: #1890ff;
  background: linear-gradient(135deg, #e6f7ff 0%, #f0f9ff 100%);
  box-shadow: 0 4rpx 12rpx rgba(24, 144, 255, 0.15);
}

.type-icon {
  margin-bottom: 12rpx;
}

.type-text {
  font-size: 26rpx;
  color: #666;
}

.type-item.active .type-text {
  color: #1890ff;
}

/* 地址选择 */
.address-tags {
  display: flex;
  gap: 16rpx;
  margin-bottom: 20rpx;
}

.address-tag {
  flex: 1;
  padding: 20rpx 16rpx;
  background-color: #fff;
  border: 1rpx solid #e6e6e6;
  border-radius: 12rpx;
  text-align: center;
  color: #666;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);
  transition: all 0.2s;
  min-width: 0;
  overflow: hidden;
}

.address-tag-text {
  font-size: 26rpx;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  display: block;
  line-height: 40rpx;
}

.address-tag.active {
  border-color: #1890ff;
  background: linear-gradient(135deg, #e6f7ff 0%, #f0f9ff 100%);
  box-shadow: 0 4rpx 12rpx rgba(24, 144, 255, 0.15);
}

.address-tag.active .address-tag-text {
  color: #1890ff;
  font-weight: 500;
}

.street-input-wrapper {
  margin-top: 20rpx;
}

.street-input {
  width: 100%;
  height: 88rpx;
  padding: 0 24rpx;
  background-color: #fff;
  border: 1rpx solid #e6e6e6;
  border-radius: 12rpx;
  font-size: 30rpx;
  color: #333;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);
  transition: all 0.2s;
}

.street-input:focus {
  border-color: #1890ff;
  box-shadow: 0 2rpx 12rpx rgba(24, 144, 255, 0.15);
}

/* 上传区域 */
.upload-area {
  border: 2rpx dashed #e6e6e6;
  border-radius: 16rpx;
  height: 200rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  background: linear-gradient(135deg, #fafbfc 0%, #fff 100%);
  transition: all 0.2s;
}

.upload-area:active {
  border-color: #1890ff;
  background: linear-gradient(135deg, #f0f9ff 0%, #e6f7ff 100%);
}

.upload-area-voucher {
  border: 2rpx dashed #e6e6e6;
  border-radius: 16rpx;
  height: 200rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  background: linear-gradient(135deg, #fafbfc 0%, #fff 100%);
  transition: all 0.2s;
}

.upload-area-voucher:active {
  border-color: #1890ff;
  background: linear-gradient(135deg, #f0f9ff 0%, #e6f7ff 100%);
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.upload-text {
  margin-top: 16rpx;
  color: #999;
  font-size: 26rpx;
}

.upload-note {
  position: absolute;
  bottom: 20rpx;
  left: 50%;
  transform: translateX(-50%);
  color: #ff9500;
  font-size: 24rpx;
}

.cert-title-container {
  display: flex;
  align-items: baseline;
  flex-wrap: wrap;
}

.upload-note-inline {
  color: #ff9500;
  font-size: 24rpx;
  margin-left: 10rpx;
  line-height: 1;
}

.warning-text {
  text-align: center;
  color: #ff4d4f;
  font-size: 26rpx;
  font-weight: 500;
}

.upload-preview-container {
  position: relative;
  width: 100%;
  height: 180rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.preview-image {
  max-width: 100%;
  max-height: 100%;
  display: block;
}

.change-btn {
  position: absolute;
  top: 20rpx;
  right: 20rpx;
  background-color: rgba(0, 0, 0, 0.5);
  color: #fff;
  font-size: 24rpx;
  padding: 10rpx 20rpx;
  border-radius: 20rpx;
  z-index: 10;
}

/* 添加产品按钮 */
.add-product-btn {
  margin-top: 40rpx;
  padding: 28rpx;
  background: linear-gradient(135deg, #fff 0%, #f0f9ff 100%);
  border: 2rpx solid #1890ff;
  border-radius: 50rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #1890ff;
  box-shadow: 0 4rpx 12rpx rgba(24, 144, 255, 0.1);
  transition: all 0.3s;
}

.add-product-btn:active {
  transform: scale(0.98);
  box-shadow: 0 2rpx 8rpx rgba(24, 144, 255, 0.2);
}

.add-text {
  margin-left: 10rpx;
  font-size: 30rpx;
  font-weight: 500;
}

/* 提交按钮 */
.submit-btn {
  width: 100%;
  height: 88rpx;
  background: linear-gradient(135deg, #e8e8e8 0%, #d9d9d9 100%);
  color: #fff;
  border: none;
  border-radius: 44rpx;
  margin-top: 40rpx;
  font-size: 34rpx;
  font-weight: 600;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
}

.submit-btn-active {
  background: linear-gradient(135deg, #73d13d 0%, #52c41a 100%) !important;
  box-shadow: 0 6rpx 20rpx rgba(82, 196, 26, 0.3) !important;
}

.submit-btn-active:active {
  transform: scale(0.98);
}

/* 已添加产品区域 */
.added-products-section {
  margin-bottom: 30rpx;
}

.added-product-item {
  background: linear-gradient(135deg, #f0f9ff 0%, #e6f7ff 100%);
  border-radius: 16rpx;
  padding: 24rpx;
  margin-bottom: 20rpx;
  border: 1rpx solid #bae7ff;
  box-shadow: 0 2rpx 8rpx rgba(24, 144, 255, 0.08);
  position: relative;
  transition: all 0.2s;
}

.added-product-item:active {
  transform: scale(0.99);
  box-shadow: 0 1rpx 4rpx rgba(24, 144, 255, 0.12);
}

.product-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15rpx;
  padding: 10rpx;
  border-radius: 8rpx;
  cursor: pointer;
}

.product-header-hover {
  background-color: rgba(0, 0, 0, 0.05);
}

.product-title {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
}

.expand-icon {
  display: flex;
  align-items: center;
  gap: 8rpx;
}

.expand-text {
  font-size: 24rpx;
  color: #999;
}

.product-summary {
  padding: 15rpx 0;
  border-bottom: 1rpx solid rgba(0, 0, 0, 0.06);
}

.summary-title {
  display: block;
  font-size: 30rpx;
  color: #333;
  font-weight: 500;
  margin-bottom: 8rpx;
}

.summary-subtitle {
  display: block;
  font-size: 28rpx;
  color: #666;
}

/* 产品资质样式 */
.product-qualifications {
  padding: 20rpx 0;
  border-bottom: 1rpx solid rgba(0, 0, 0, 0.06);
}

.qualifications-title {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
  margin-bottom: 15rpx;
}

.qualifications-container {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.qualification-item {
  flex: 1;
  min-width: 45%;
}

.qualification-label {
  display: block;
  font-size: 24rpx;
  color: #666;
  margin-bottom: 8rpx;
}

.qualification-image {
  width: 100%;
  height: 150rpx;
  border-radius: 8rpx;
  border: 1rpx solid #e6e6e6;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.product-details {
  padding-top: 20rpx;
}

.product-edit-form {
  padding-top: 20rpx;
  border-top: 1rpx solid rgba(0, 0, 0, 0.06);
}

.product-edit-form .form-row {
  margin-bottom: 20rpx;
}

.product-edit-form .section-area {
  margin-top: 20rpx;
}

.current-product-form {
  background: #fff;
  border-radius: 20rpx;
  padding: 30rpx;
  margin: 20rpx;
}

.form-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 20rpx;
  padding-bottom: 20rpx;
  border-bottom: 2rpx solid #f0f0f0;
}

.save-btn {
  background-color: rgba(24, 144, 255, 0.1);
  margin-right: 20rpx;
}

.save-text {
  color: #1890ff;
  margin-left: 8rpx;
  font-size: 24rpx;
}

.detail-row {
  display: flex;
  padding: 12rpx 0;
}

.detail-label {
  font-size: 26rpx;
  color: #999;
  width: 180rpx;
}

.detail-value {
  flex: 1;
  font-size: 26rpx;
  color: #333;
}

.cert-status {
  color: #52c41a;
}

.detail-actions {
  display: flex;
  justify-content: flex-end;
  padding-top: 20rpx;
  border-top: 1rpx solid rgba(0, 0, 0, 0.06);
  margin-top: 20rpx;
}

.detail-btn {
  display: flex;
  align-items: center;
  padding: 10rpx 20rpx;
  border-radius: 20rpx;
  border: 1rpx solid #ff4d4f;
}

.delete-btn {
  background-color: rgba(255, 77, 79, 0.1);
}

.delete-text {
  font-size: 24rpx;
  color: #ff4d4f;
  margin-left: 8rpx;
}

/* 须知弹窗样式 */
.notice-container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 9999;
  display: flex;
  align-items: center;
  justify-content: center;
}

.mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
}

.notice-popup {
  position: relative;
  width: 90%;
  max-width: 600rpx;
  background-color: #fff;
  border-radius: 20rpx;
  padding: 40rpx;
  box-shadow: 0 10rpx 40rpx rgba(0, 0, 0, 0.2);
}

.notice-title {
  display: block;
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  text-align: center;
  margin-bottom: 40rpx;
}

.notice-content {
  max-height: 600rpx;
  overflow-y: auto;
}

.notice-section {
  margin-bottom: 30rpx;
}

.section-title {
  display: block;
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
}

.notice-item {
  display: flex;
  margin-bottom: 20rpx;
  align-items: flex-start;
  padding-left: 20rpx;
}

.item-number {
  color: #ff9800;
  font-size: 32rpx;
  font-weight: bold;
  margin-right: 20rpx;
  flex-shrink: 0;
}

.item-text {
  flex: 1;
  font-size: 28rpx;
  color: #666;
  line-height: 1.6;
}

.confirm-btn {
  width: 100%;
  height: 88rpx;
  background: linear-gradient(135deg, #ff9800 0%, #ff6b00 100%);
  color: #fff;
  font-size: 32rpx;
  font-weight: bold;
  border-radius: 44rpx;
  border: none;
  margin-top: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.confirm-btn:active {
  opacity: 0.8;
}
</style>
